// import axios from 'axios'

// export function request(config){
//   const instance = axios.create({
//     baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net/',
//     timeout:5000
//   })

//   instance.interceptors.request.use(config => {
//     return config
//   }, err => {
//     return Promise.reject(err)
//   })

//   instance.interceptors.response.use(res => {
//     return res.data
//   }, err => {
//     return Promise.reject(err)
//   })

//   return instance(config)
// }

import axios from 'axios'

import store from '@/store'
import router from '@/router'

export const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net/'
const instance = axios.create({
  baseURL,
  timeout:5000
})

instance.interceptors.request.use(config => {
  // 1.获取用户对象信息
  const { profile } = store.state.user
  // 2.判断是否有token 
  if(profile.token) {
    config.headers.Authorization = `Bearer ${profile.token}`
  }
  return config
}, err => {
  return Promise.reject(err)
})

instance.interceptors.response.use(res => {
  return res.data
}, err => {
  // 401状态码，进入该函数
  if(err.response && err.response.status === 401) {
    // 1. 清空无效用户信息
    // 2. 跳转到登录页
    // 3. 跳转需要传参（当前路由地址）给登录页码
    store.commit('user/setUser',{})
    const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
    router.push('/login?redirectUrl=' + fullPath)

  }
  return Promise.reject(err)
})

// 请求工具函数
export default(url,method,submitData) => {
  return instance({
    url,
    method,
    [method.toLowerCase() === 'get'?'params':'data']:submitData
  })
}